<script setup>
import { ref, onMounted } from 'vue'
import Split from 'split.js'
import Editor from "../components/Editor.vue";
import { Schema, Query, ReadFile, WriteFile } from "../../wailsjs/go/main/App";
import { useRoute } from 'vue-router';
import "highlight.js/styles/atom-one-dark.css";
import hljs from "highlight.js/lib/common"
import { Eta } from "eta"

const eta = new Eta({ tags: ["{{", "}}"] })
const router = useRoute()
const filename = router.query.path;

const editorRef = ref();
const results = ref("")
const tmpl = ref("")
const metadata = ref({ name: "John Doe" });
const loadData = () => {
    ReadFile(filename).then((data) => {
        tmpl.value = data
        editorRef.value.setValue(data)
    })
}
const isChange = ref(false)
const handleSave = () => {
    WriteFile(filename, tmpl.value).then(() => {
        isChange.value = false
    })
}
const handleChange = (value) => {
    isChange.value = false
    tmpl.value = value
    results.value = hljs.highlightAuto(eta.renderString(tmpl.value, metadata.value)).value;
}

const handleSchema = () => {
    Schema(form.value.dsn).then(res => {
        results.value = JSON.stringify(res, null, 2);
    })
}
const handleQuery = () => {
    Query(form.value.dsn, form.value.sqlstr, true).then(res => {
        results.value = JSON.stringify(res, null, 2);
    })
}

onMounted(() => {
    Split(['#template-left', '#template-right'], {
        sizes: [50, 50],
        minSize: [100, 100],
        gutterSize: 6,
    })
    loadData();
})
</script>
<template>
    <div class="flex w-full h-full">
        <div id="template-left">
            <a-tabs default-active-key="1" class="w-full h-full" size="mini">
                <a-tab-pane key="1" title="Tab 1">
                    <a-button v-if="isChange">保存</a-button>
                    <Editor ref="editorRef" language="html" @change="handleChange" @save="handleSave" />
                </a-tab-pane>
                <a-tab-pane key="2" title="Tab 2">
                    {{ metadata }}
                </a-tab-pane>
            </a-tabs>
        </div>
        <div id="template-right">
            <div class="w-full h-full flex flex-col">
                <div class="border-b border-color h-7 flex items-center gap-2 px-1"></div>
                <a-scrollbar class="overflow-auto w-full h-full" outer-class="w-full h-0 flex-1">
                    <pre><code v-html="results"></code></pre>
                </a-scrollbar>
            </div>
        </div>
    </div>

</template>